import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FormlyFieldConfig, FormlyFormOptions } from '@ngx-formly/core';
import { ApiService } from '@core/services/http/api.service';
import { dateFormat, deepClone, fillField, replaceAll, type } from '../../../../../utils/utils';
import { BiService } from '../../../bi.service';
import { AssemblyDrawingDialogComponent } from '../../../../assemblyDrawing/assemblyDrawing-dialog.component';
import { ApesModalRef, ApesModalService } from '@shared/apes/modal';
import { AllModules, Module } from '@ag-grid-enterprise/all-modules';
import { GridOptions } from '@ag-grid-community/core';
import { GridConfigService } from '@core/config/grid-config.service';
import { ExportExcelService } from '@core/services/excel/export-excel.service';
import { ApesMessageService } from '@shared/apes/message';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { XlsxService } from '@shared/apes/xlsx';

@Component({
  selector: 'technical-review-dialog',
  template: `
    <div apes-row [apesGutter]="16" class="apes-item" style="padding: 16px;">
      <formly-form [model]="model" [fields]="conditionField"></formly-form>
      <div apes-col [apesSpan]="2">
        <button apes-button apesType="primary" [apesSize]="'default'" (click)="queryData()">查询</button>
      </div>
      <div apes-col [apesSpan]="2">
        <button apes-button [apesSize]="'default'" (click)="onBtDownload()" [disabled]="isDownloading">下载</button>
      </div>
    </div>
    <div apes-row apesGutter="24" apesSpan="16">
      <div apes-col [apesSpan]="24">
        <ag-grid-angular #grid
                         style="width: 100%;" [ngStyle]="{ height: height }" class="ag-theme-balham"
                         enableColResize="true"
                         enableSorting="true"
                         suppressLoadingOverlay="true"
                         [modules]="modules"
                         [rowData]="rowData"
                         [headerHeight]="50"
                         [gridOptions]="gridOptions"
                         [columnDefs]="columnDefs"
                         [frameworkComponents]="frameworkComponents"
                         [localeText]="localeText"
                         [rowModelType]="rowModelType"
                         (gridReady)="onGridReady($event)">
        </ag-grid-angular>
        <div class="apes-paging" *ngIf="rowModelType=='serverSide'">
          已加载{{loadingTotal}}行，总行数{{pagination.total}}
        </div>
      </div>
    </div>
  `,
})
export class TechnicalReviewDialogComponent implements OnInit {

  // 技术审核退回原因
  conditionField: FormlyFieldConfig[] = [
    {
      key: 'DEPT_ID',
      type: 'conditionInput',
      templateOptions: {
        label: '所属门店',
        config: {
          api: 'cm.dept.findAll',
          init: true,
          operators: ['EQ'],
          type: 'select',
          downFormatter: 'value.name',
          multiple: true,
          valueFormatter: 'value.name',
          searchFormId: 'cm.dept.findAllWithAccessProvider',
          rowSelection: 'multiple',
          addSame: false,
          uniqueKey: 'id',
        },
        domain: '{"filters":[{"field":"id","operator":"LIKE","value":"{{value}}"},{"field":"name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}',
        divCol: 6,
      },
    },
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'dateRange',
        },
        divCol: 6,
      },
    },
  ];
  // returnData: any;
  model: any = {};
  returnLoading: boolean = false;
  api: any = 'fn.tech.qryBackPriceAuditDetail';

  /** grid 相关 **/
  modules: Module[] = AllModules;
  rowData: any[] = [];
  height: any = 520 + 'px';
  gridOptions: GridOptions;
  columnDefs: any = [];
  frameworkComponents;
  localeText: any;
  rowSelection: any;
  gridApi: any;

  /** 分页器 **/
  downloadPage = 0;
  isDownloading = false;
  loadingTotal = 0;
  pagination = {
    total: 0,
    currentPage: 1,
    lastRow: -1,
    pageSize: 50,
  };
  percent = 0;
  rowModelType = 'serverSide';

  constructor(
    private apiService: ApiService,
    protected expressionService: ExpressionService,
    private modal: ApesModalRef,
    private msg: ApesMessageService,
    private gridConfigService: GridConfigService,
    private  xlsx: XlsxService,
    private bi: BiService,
  ) {
    this.columnDefs = [
      { headerName: '门店', field: 'DEPT_NAME' },
      { headerName: '服务方案号', field: 'PLAN_ID' },
      { headerName: '审批退回意见', field: 'TECH_AUDIT_OPINION' },
      { headerName: '审批人', field: 'BACK_NAME' },
      { headerName: '审批日期', field: 'BACK_DATE' },
    ];
    this.localeText = gridConfigService.getLocaleText();
    this.gridOptions = <GridOptions>{
      suppressExcelExport: true,
      suppressCsvExport: true,
      showToolPanel: false,
    };
  }

  ngOnInit() {
    this.rowModelType = 'serverSide';
    this.gridOptions.cacheBlockSize = 50;
    this.gridOptions.infiniteInitialRowCount = 1;
    this.gridOptions.pagination = false;
    this.gridOptions.paginationPageSize = this.pagination.pageSize;

  }

  queryData() {
    let date = this.bi.conversionMonths(this.model['DATE'], 6);
    let id = this.model['DEPT_ID'] ? this.model['DEPT_ID'] : [];

    const data = {
      DEPT_ID: id,
      DATE_START: date[0],
      DATE_END: date[1],
    };

    const sendData = {};
    sendData['condition'] = data;

    this.returnLoading = true;

    let dataSource = {
      rowCount: null,
      getRows: (params: any) => this.getRows(params, [], sendData),
    };
    this.gridApi.setServerSideDatasource(null);
    this.gridApi.setServerSideDatasource(dataSource);
  }

  private getRows(params: any, data: any, sendData: any) {
    sendData['size'] = this.pagination.pageSize;
    sendData['page'] = this.pagination.currentPage;
    // TODO 检查返回值是否不为空数组
    this.apiService.post(this.api, {'body': JSON.stringify(sendData)})
      .subscribe((items) => {
        if (items) {

          this.pagination.total = items.total;
          const itemsLength = items.content.length;
          if (itemsLength > 0 && itemsLength >= this.pagination.pageSize) {
            this.pagination.currentPage = this.pagination.currentPage + 1;
          }
          if (itemsLength == 0 || itemsLength < this.pagination.pageSize) {
            this.pagination.lastRow = (this.pagination.currentPage - 1) * this.pagination.pageSize + itemsLength;
          }

          this.loadingTotal = this.pagination.lastRow !== -1 ? this.pagination.lastRow : params.request.endRow;
          let bHJ = true;
          if (itemsLength > this.pagination.pageSize || !items.hasOwnProperty("pages")) {
            this.pagination.lastRow = itemsLength;
            this.loadingTotal = itemsLength;
            if (this.pagination.currentPage > 2) {
              bHJ = false;
            }
          }

          params.successCallback(items.content, this.pagination.lastRow);
          if (itemsLength === 0 && this.pagination.lastRow <= 0) this.msg.info(`未找到满足条件的数据`);
        } else {
          params.successCallback([], 0);
        }
      }, () => {

      });
  }

  onGridReady(params) {
    this.gridApi = params.api;
  }

  /**
   * 功能：获取表格数据
   * @returns {any[]}
   */
  private getRow(): any[] {
    let rows = [];
    this.gridApi.forEachNode((node) => {
      rows.push(node.data);
    });
    return rows;
  }

  /**
   * 下载
   */
  onBtDownload() {
    let downloadData = [];
    let col = [];
    let total = this.pagination.total;
    this.columnDefs.forEach((i) => {
      col.push(i);
    });
    //初始化下载变量
    this.downloadPage = 1;
    if (total > this.getRow().length) {
      this.isDownloading=true;
      this.queryDownloadData(downloadData,col)
    } else {
      downloadData = this.getRow();
      this.generateExcl(downloadData, col);
    }
  }

  /**
   * 功能：查询后台数据(下载)
   */
  private queryDownloadData(data, col) {

    let date = this.bi.conversionMonths(this.model['DATE'], 6);
    let id = this.model['DEPT_ID'] ? this.model['DEPT_ID'] : [];

    let conditionData = {
      DEPT_ID: id,
      DATE_START: date[0],
      DATE_END: date[1],
    };

    const sendData = {};
    sendData['condition'] = conditionData;
    sendData['size'] = 3000;
    sendData['page'] = this.downloadPage;

    this.apiService.post(this.api, {'body': JSON.stringify(sendData)}).subscribe(
      (body) => {
        if (body) {

          if (body.size) this.pagination.pageSize = body.size;
          body.content.forEach((i) => {
            data.push(i);
          })
          if (this.pagination.total <= data.length || this.downloadPage >= 30) {
            if (this.downloadPage >= 30){
              this.msg.info(`数据量过大！目前仅支持9W行数据下载`)
            }
            this.generateExcl(data, col);
            this.isDownloading=false;
          } else {
            this.downloadPage = this.downloadPage + 1;
            this.queryDownloadData(data, col)
          }
        }else {
          this.msg.info(`下载接口报错！`)
        }
      }, () => {

      });
  }

  /**
   * 生成excl
   * @param downloadData
   * @param col
   * @private
   */
  private generateExcl(downloadData, col) {
    let data = [];
    data = [col.map(i => i.headerName)];
    downloadData.forEach(i =>
      data.push(
        col.map(c => {
            let value = deepClone(i[c.field as string]);
            if (value instanceof Object) {
              if (c['exportFormatter']) {
                let expression = c['exportFormatter'];
                value = this.expressionService.evaluate(expression, {
                  value: value,
                });
              } else {
                value = value.name;
              }
              if (value == undefined) {
                value = i[c.field as string].description;
              }
            }
            // 处理序号字段为空的问题
            if (c.field === 'operation') value = data.length;

            return value;
          },
        )),
    );
    this.xlsx.export({
      filename: '技术审核退回原因.xlsx',
      sheets: [
        {
          data: data,
          name: 'sheet name',
        },
      ],
    });
  }

  destroyModal(): void {
    this.modal.destroy();
  }
}

